<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.expensescost_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.expensescost_edit"
                   @click="handleExport">导出
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/restaurant/expensescost";
  import {mapGetters} from "vuex";
  import { getToken } from '@/utils/auth';
  import { serialize } from '@/utils/util';
  import { getLevelTree } from '@/api/restaurant/common';
  import { baseUrl } from '@/config/env';
  import func from '@/utils/func';

  export default {
    data() {
      return {
        form: {},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          showSummary: true,
          sumColumnList: [
            { name: 'dailyExpendAmount', type: 'sum' , decimals: 2 }
          ],
          column: [
            {
              label: '日期',
              hide: true,
              prop: 'searchTime',
              type: 'date',
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              search: true,
              searchSpan: 8,
              searchRange: true,
              editDisplay: false, // 编辑隐藏
              addDisplay: false, // 新增隐藏
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            {
              label: "日期",
              prop: "time",
              type: 'date',
              format: 'YYYY-MM-DD',
              valueFormat: 'YYYY-MM-DD',
              rules: [{
                required: true,
                message: "请输入日期",
                trigger: "blur"
              }]
            },
            {
              label: "分类",
              prop: 'classification',
              type: 'cascader',
              props: {
                label: 'title'
              },
              dicUrl: baseUrl + "/restaurant/common/getLevelTree",
              rules: [{
                required: true,
                message: "请输入分类",
                trigger: "blur"
              }],
            },
            {
              label: "明细名称",
              prop: "name",
              search: true,
              rules: [{
                required: true,
                message: "请输入明细名称",
                trigger: "blur"
              }]
            },
            {
              label: "支出",
              prop: "dailyExpendAmount",
              type: 'number',
              precision: 2,
              min: 0,
              rules: [{
                required: true,
                message: "请输入支出",
                trigger: "blur"
              }]
            },
            {
              label: "是否均摊",
              type: "switch",
              prop: "isAvg",
              dicData: [{
                label: '否',
                value: 0
              }, {
                label: '是',
                value: 1
              }],
              search: true,
              rules: [{
                required: true,
                message: "请输入是否均摊",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remark",
              type: "textarea",
              overHidden: true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            {
              label: "附件",
              prop: "enclosure",
              type: "upload",
              overHidden: true,
              listType: "picture-card",
              action: "/api/blade-resource/oss/endpoint/put-file",
              propsHttp: {
                res: 'data',
                url: 'link'
              },
              rules: [{
                required: false,
                message: "请输入附件",
                trigger: "blur"
              }]
            },

          ]
        },
        data: [],
        classificationDicData:[]
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.expensescost_add, false),
          viewBtn: this.validData(this.permission.expensescost_view, false),
          delBtn: this.validData(this.permission.expensescost_delete, false),
          editBtn: this.validData(this.permission.expensescost_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      async handleExport() {
        this.$confirm(`确定导出费用支出数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.open(`/api/restaurant/expensescost/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
        });
      },
      classificationTitle(val1,val2) {
        const pItem = this.classificationDicData.find(item => item.id === val1)
        let text = pItem.title
        if (val2) {
          const cItem = pItem.children.find(item => item.id === val2)
          text += ' | ' + cItem.title
        }
        return text;
      },
      rowSave(row, done, loading) {
        row.classificationText = this.classificationTitle(row.classification[0], row.classification[1])

        if (Array.isArray(row.enclosure)) {
          row.enclosure =func.join(row.enclosure);
        }
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        row.classificationText = this.classificationTitle(row.classification[0], row.classification[1])
        if (Array.isArray(row.enclosure)) {
          row.enclosure =func.join(row.enclosure);
        }
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      getClassificationDicData(){
        getLevelTree().then(res => {
          this.classificationDicData = res.data.data;
        });
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;

          this.getClassificationDicData()

          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
